package com.situ.controller;

import com.mysql.cj.Session;
import com.situ.util.ImageUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/image")
public class ImageController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 返回值类型为image图片
        response.setContentType("image/jpeg");
        // 禁止图片缓存
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        int times = 0;
        String str=new String();
        while(times < 4) {
            char rand = (char) (Math.random( ) * 26 + 65);
            str+=rand;
            times++;
        }



        ServletOutputStream sos = response.getOutputStream();

        HttpSession session = request.getSession();
        session.setAttribute("captcha", str);

        ImageIO.write(ImageUtil.image(str),"JPEG",sos);// 流写出图像
        // 释放资源
         sos.flush();
         sos.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }


}